package git.luohao.datasource;

import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.datasource.WritableDataSource;
import com.alibaba.csp.sentinel.log.RecordLog;
import org.springframework.jdbc.core.JdbcTemplate;

import java.io.File;
import java.io.FileOutputStream;
import java.nio.charset.Charset;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DBWritableDataSource<T> implements WritableDataSource<T> {
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
    private final Converter<T, String> configEncoder;
    private JdbcTemplate jdbcTemplate;
    private final Charset charset;
    private final Lock lock;

    public DBWritableDataSource(JdbcTemplate jdbcTemplate, Converter<T, String> configEncoder) {
        this(jdbcTemplate, configEncoder, DEFAULT_CHARSET);
    }

    public DBWritableDataSource(JdbcTemplate jdbcTemplate, Converter<T, String> configEncoder, Charset charset) {
        this.lock = new ReentrantLock(true);
        this.configEncoder = configEncoder;
        this.jdbcTemplate = jdbcTemplate;
        this.charset = charset;
    }

    public void write(T value) throws Exception {
        this.lock.lock();
        try {
            String convertResult = (String)this.configEncoder.convert(value);
//[{"clusterMode":false,"controlBehavior":0,"count":1.0,"grade":1,"limitApp":"default","maxQueueingTimeMs":500,"resource":"/hello2","strategy":0,"warmUpPeriodSec":10},{"clusterMode":false,"controlBehavior":0,"count":3.0,"grade":1,"limitApp":"default","maxQueueingTimeMs":500,"resource":"/hello","strategy":0,"warmUpPeriodSec":10}]
            System.out.println("准备写入数据库：" + convertResult);
        } finally {
            this.lock.unlock();
        }

    }

    public void close() throws Exception {
    }
}
